package com.tarry.service.impl;

import com.google.common.base.Preconditions;
import com.tarry.common.RequestHolder;
import com.tarry.dao.SysAclMapper;
import com.tarry.dao.SysAclModuleMapper;
import com.tarry.exception.ParamException;
import com.tarry.model.entity.SysAclModule;
import com.tarry.model.vo.AclModuleVo;
import com.tarry.service.SysAclModuleService;
import com.tarry.util.BeanValidator;
import com.tarry.util.IpUtil;
import com.tarry.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SysAclModuleServiceImpl extends BaseService<SysAclModule> implements SysAclModuleService {

    @Autowired
    private SysAclModuleMapper sysAclModuleMapper;
    @Autowired
    private SysAclMapper sysAclMapper;


    @Override
    public SysAclModule findByKeyword(String keyword) {
        return null;
    }

    @Override
    public void save(AclModuleVo entity) {
        BeanValidator.check(entity);
        if(checkExist(entity.getParentId(), entity.getName(), entity.getId())) {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule aclModule = SysAclModule
                .builder()
                .name(entity.getName())
                .parentId(entity.getParentId())
                .seq(entity.getSeq())
                .status(entity.getStatus())
                .remark(entity.getRemark())
                .build();
        aclModule.setLevel(LevelUtil.calculateLevel(
                getLevel(entity.getParentId()),
                entity.getParentId()));
        setOpratorInfo(aclModule);
        sysAclModuleMapper.insertSelective(aclModule);
        //sysLogService.saveAclModuleLog(null, aclModule);

    }

    @Override
    public void update(AclModuleVo entity) {
        BeanValidator.check(entity);
        if(checkExist(entity.getParentId(), entity.getName(), entity.getId())) {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule before = sysAclModuleMapper.selectByPrimaryKey(entity.getId());
        Preconditions.checkNotNull(before, "待更新的权限模块不存在");

        SysAclModule after = SysAclModule.builder()
                .id(entity.getId())
                .name(entity.getName())
                .parentId(entity.getParentId())
                .seq(entity.getSeq())
                .status(entity.getStatus())
                .remark(entity.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(entity.getParentId()), entity.getParentId()));
        setOpratorInfo(after);
        updateWithChild(before, after);
        //sysLogService.saveAclModuleLog(before, after);

    }


    @Transactional
    public void updateWithChild(SysAclModule before, SysAclModule after) {
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        if (!after.getLevel().equals(before.getLevel())) {
            List<SysAclModule> aclModuleList =
                    sysAclModuleMapper.getChildAclModuleListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(aclModuleList)) {
                for (SysAclModule aclModule : aclModuleList) {
                    String level = aclModule.getLevel();
                    if (level.indexOf(oldLevelPrefix) == 0) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        aclModule.setLevel(level);
                    }
                }
                sysAclModuleMapper.batchUpdateLevel(aclModuleList);
            }
        }
        sysAclModuleMapper.updateByPrimaryKeySelective(after);
    }


    @Override
    public void delete(int id) {
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(id);
        Preconditions.checkNotNull(aclModule, "待删除的权限模块不存在，无法删除");
        if(sysAclModuleMapper.countByParentId(aclModule.getId()) > 0) {
            throw new ParamException("当前模块下面有子模块，无法删除");
        }
        if (sysAclMapper.countByAclModuleId(aclModule.getId()) > 0) {
            throw new ParamException("当前模块下面有用户，无法删除");
        }
        sysAclModuleMapper.deleteByPrimaryKey(id);

    }

    private boolean checkExist(Integer parentId, String aclModuleName, Integer deptId) {
        return sysAclModuleMapper.countByNameAndParentId(parentId, aclModuleName, deptId) > 0;
    }

    private String getLevel(Integer aclModuleId) {
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        if (aclModule == null) {
            return null;
        }
        return aclModule.getLevel();
    }

}
